var JQUERY_DATA_NAME = 'scroll-tab';
var seq = Date.now();

function TabItem(options) {
    this.title = options.title;
    this.$title = options.$title;
    this.$content = options.$content;
    this.name = options.name;
    this.isActive = false;
}

TabItem.prototype.active = function() {
    this.isActive = true;
    this.$title.addClass('selectedTab');
    this.$content.addClass('selectedContent');
};

TabItem.prototype.deactive = function() {
    this.isActive = false;
    this.$title.removeClass('selectedTab');
    this.$content.removeClass('selectedContent');
};

function ScrollTabComponent($elm, options) {
    this.$element = $elm;
    this.options = options;
    this.tabs = [];
    this.tabMap = {};
}

ScrollTabComponent.prototype = {
    constructor: ScrollTabComponent,
    prepare: function() {
        var $line = $('<div class="blueline">');
        var $tabgrp = $('<ul class="tabGroup">');
        var $tabbody = $('<div class="tabBody">');

        this.$element.addClass('tabmain');
        this.$element.append($line);
        this.$element.append($tabgrp);
        this.$element.append($tabbody);

        this.$grp = $tabgrp;
        this.$body = $tabbody;
        this.$line = $line;
        var component = this;

        $tabgrp.on('click', '.tabOption', function() {
            var name = $(this).attr('tab-name');
            component.active(name);
        });
        var self = this;
        self._triggerScrollBySelf = false;
        $tabbody.on('scroll', function(e) {
            if (self._triggerScrollBySelf) {
                return;
            }
            var scrollTop = $tabbody.scrollTop();
            var tabTop = 0;
            for (var i = 0; i < self.tabs.length; i++) {
                var tab = self.tabs[i];
                var ofs = scrollTop - tabTop;
                var outerHeight = tab.$content.outerHeight();
                if (ofs >= 0 && ofs < outerHeight / 3) {
                    self.active(tab.name, false);
                    break;
                }
                tabTop += outerHeight;
            }
        });
    },
    addTab: function(tabConfig) {
        var tab = this._createTab(tabConfig);
        if (this.tabMap[tab.name]) {
            throw new Error('Duplicated tab name');
        }
        this.$grp.append(tab.$title);
        this.$body.append(tab.$content);
        this.tabMap[tab.name] = tab;
        this.tabs.push(tab);
        if (tabConfig.active) {
            this.active(tab.name);
        }
        return tab;
    },
    _createTab: function(tabConfig) {
        var name = tabConfig.name || (seq++).toString(16);
        var title = tabConfig.title || '';

        var $title = $('<li class="tabOption">');
        var $content = $('<div class="tabContent">');

        $title.text(title);
        $title.attr('id', name + "_title");
        $title.attr('tab-name', name);
        $content.attr('id', name + "_content");
        $content.attr('tab-name', name);
        $content.append(tabConfig.body);
        $content.find("h3").text(title);
        let $files = [];
        $.each(tabConfig.files, function(index, item) {
            let $file = $(`<li class="file" data-id=` + item.id + `>
              <p class="imgWrap">
                  <img src="api/` + item.url + `">
              </p>
              <div class="file-panel">
                  <span class="cancel" data-id=` + item.id + `></span>
                  <span class="title">` + item.name + `</span>
              </div>
          </li>`);
            $file.on("click", ".cancel", function() {
                $.myAjax({
                    url: "ad/delAdFile.do",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify({
                        fileId: item.id
                    }),
                    success: function(result) {
                        $file.off().find('.file-panel').off().end().remove();
                    }
                });
            });
            $files.push($file);
        });
        $content.find(".filelist").prepend($files);

        return new TabItem({
            $title: $title,
            $content: $content,
            name: name,
            title: title
        });
    },
    active: function(name, scroll) {
        for (var i = 0; i < this.tabs.length; i++) {
            var tabk = this.tabs[i];
            if (tabk.name !== name && tabk.isActive) {
                tabk.deactive();
            }
        }
        var tab = this.tabMap[name];
        if (tab.isActive) {
            return;
        }
        tab.active();
        var animateTime = 300;
        this.$line.animate({
            top: tab.$title.position().top
        }, animateTime);

        if (scroll !== false) {
            var scrollTop = 0;
            for (var j = 0; j < this.tabs.length; j++) {
                var tabj = this.tabs[j];
                if (tabj === tab) {
                    break;
                }
                scrollTop += $(tabj.$content).outerHeight();
            }
            var self = this;
            self._triggerScrollBySelf = true;
            this.$body.stop().animate({
                scrollTop: scrollTop
            }, animateTime, 'swing', function() {
                self._triggerScrollBySelf = false;
            });
        }
    },
    destroy: function() {
        this.$element.remove();
        this.tabs = [];
        this.tabMap = {};
    }
};

$.fn.scrltab = function() {
    var args = arguments;
    return this.each(function(i, item) {
        var $item = $(item);
        $item._scrltab.apply($item, args);
    });
};

$.fn._scrltab = function(options) {
    if (this.length !== 1) {
        throw new Error('illegal operation');
    }
    var tab = this.data(JQUERY_DATA_NAME);
    if (!tab) {
        if (typeof options === 'string') {
            tab = new ScrollTabComponent(this, {});
        } else {
            tab = new ScrollTabComponent(this, options);
        }
        this.data(JQUERY_DATA_NAME, tab);
        tab.prepare();
    }
    if (typeof options === 'string') {
        tab[options].apply(tab, Array.prototype.slice.call(arguments, 1));
    }
    return this;
};
